package com.qst.medical.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qst.medical.domain.Sale;
import com.qst.medical.entity.SaleEntity;
import com.qst.medical.mapper.SaleMapper;
import com.qst.medical.util.Msg;
import com.qst.medical.entity.SaleEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class SaleService {
    @Autowired
    private SaleMapper saleMapper;
    public PageInfo<Sale> getSaleWithPage(Integer pn, Integer size, String name) {
        if (pn ==null && size == null) {
            pn = 1;
            size = Integer.MAX_VALUE;
        }
        if (pn == null) {
            pn = 1;
        }
        if (size == null) {
            size = Integer.MAX_VALUE;
        }
        if (size == 0) {
            size = 1;
        }
        PageHelper.startPage(pn, size);
        List<Sale> list = saleMapper.getAllSale(name);
        PageInfo<Sale> info = new PageInfo<>(list,5);
        return info;
    }
    public Msg getSaleById(Long id) {
        Sale sale = saleMapper.getSaleById(id);

        if(sale == null) {
            return Msg.fail().mess("没有找到");
        }
        return Msg.success().data("sale", sale);
    }
    //保存销售地点
    public Msg saveSale(Sale sale) {
        Date d = new Date();
        sale.setCreatetime(d);
        sale.setUpdatetime(d);
        SaleEntity se = new SaleEntity();
        BeanUtils.copyProperties(sale,se);//对象拷贝
        int i = saleMapper.saveSale(se);
        if (i > 0) {
            Long num = se.getTotal() % 5 == 0 ? (se.getTotal() / 5) : (se.getTotal() / 5)+1;
            return Msg.success().data("pages",num).mess("添加成功");
        }
        return Msg.fail().mess("添加失败");
    }
    //更新销售地点
    public Msg updateSaleById(Long id, SaleEntity sale) {
        sale.setUpdatetime(new Date());
        sale.setSaleId(id);
        int i = saleMapper.updateSaleById(sale);
        if (i > 0) {
            return Msg.success().mess("修改成功");
        }
        return Msg.fail().mess("修改失败");
    }
    //删除销售地点
    /**
     * 根据id删除医药公司信息
     * @param id
     * @return
     */
    public Msg deleteSaleById(Long id) {
        int i = saleMapper.deleteSaleById(id);
        if (i > 0) {
            return Msg.success().mess("删除成功");
        } else {
            return Msg.fail().mess("删除失败");
        }
    }
}
